package com.hcloud.libupload.http

import android.util.Log
import com.hcloud.libupload.request.UploadRequest
import com.hcloud.libupload.utils.runOnUi
import java.io.File


data class Progress(
    var uploadId: String = "",
    @Volatile
    var totalSize: Long = 0L,
    @Volatile
    var currentSize: Long = 0L,
    @Volatile
    var tempSize: Long = 0L,
    @Volatile
    var progress: Int = 0,
    @Volatile
    var speed: Long = 0L,
    @Volatile
    var lastRefreshTime: Long = 0L
) {

    private val speedBuffer = mutableListOf<Long>()


    @Synchronized
    fun progressChange(uploadRequest: UploadRequest,byteCount: Long) {

        currentSize += byteCount
        tempSize += byteCount
        val currentTime = System.currentTimeMillis()

        if (currentTime - lastRefreshTime >= 500 || currentSize >= totalSize) {
            var diffTime = currentTime - lastRefreshTime
            if (diffTime == 0L) diffTime = 1
            speed = bufferSpeed(tempSize * 1000 / diffTime)
            progress =
                if (currentSize >= totalSize) 100 else (currentSize * 100 / totalSize).toInt()
            lastRefreshTime = currentTime
            tempSize = 0L

            Log.i(
                "--progress",
                "${uploadId} ${progress} ${currentSize} ${totalSize}  ${speed}"
            )

            runOnUi {
                if (!uploadRequest.isCancel) {
                    uploadRequest.uploadTask?.iProgressCallback?.progress(uploadRequest, this)
                }
            }
        }
    }


    /** 平滑网速，避免抖动过大  */
    @Synchronized
    fun bufferSpeed(speed: Long): Long {
        speedBuffer.add(speed)
        if (speedBuffer.size > 10) {
            speedBuffer.removeAt(0)
        }
        var sum: Long = 0
        for (speedTemp in speedBuffer) {
            sum += speedTemp
        }
        return sum / speedBuffer.size
    }


    fun reset(file: File) {
        totalSize = file.length()
        currentSize = 0L
        tempSize = 0L
        speed = 0L
        lastRefreshTime = 0

        speedBuffer.clear()
    }

}